package cn.ultrarisk.scadmin.manager.biz.solr.service;

import cn.ultrarisk.mybatis.extension.query.Query;
import cn.ultrarisk.mybatis.extension.query.Updater;
import cn.ultrarisk.scadmin.manager.biz.solr.context.SolrState;
import cn.ultrarisk.scadmin.manager.biz.solr.dao.SolrShardDAO;
import cn.ultrarisk.scadmin.manager.biz.solr.entity.SolrShard;
import cn.ultrarisk.scadmin.manager.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * SolrShardService
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/5/13
 * @since V1.0
 */
@Service
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class SolrShardService {
    @Autowired
    private SolrShardDAO solrShardDAO;

    public SolrShard saveByZKInfo(String name, JsonUtil.MapWrapper shardStateMap, Integer collectionId, Long updateTime) {
        SolrShard shard = solrShardDAO.get(Query.query(SolrShard.NAME, name).eq(SolrShard.COLLECTION_ID, collectionId));
        SolrState state = SolrState.get(shardStateMap.getStringByPath(name, "state"));
        if (shard == null) {

            shard = new SolrShard(name, collectionId);
        }

        shard.setState(state);
        shard.setAvailable(true);
        shard.setUpdateTime(updateTime);

        if (shard.getId() == null) {
            solrShardDAO.create(shard);
        } else {
            solrShardDAO.update(shard.getId(), Updater.update(SolrShard.STATE, state).addField(SolrShard.AVAILABLE, true).addField(SolrShard.UPDATE_TIME, updateTime));
        }
        return shard;
    }

    public void disable(List<Integer> ids) {
        solrShardDAO.update(Query.inQuery(SolrShard.ID, ids), Updater.update(SolrShard.AVAILABLE, false));
    }

    /**
     * 清除过期的solrShard
     *
     * @query expiredTime
     */
    public void clearExpiredData(long expiredTime) {
        Query query = Query.ltQuery(SolrShard.UPDATE_TIME, expiredTime);
        solrShardDAO.delete(query);
    }
}
